package game;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;

import renderer.program.GLProgramManager;
import sys.Logger;
import sys.SysParam;

public class M5CraftEngine extends M5CraftBase {
	public static M5CraftEngine getInstance() {
		if (instance == null) {
			instance = new M5CraftEngine();
		}
		return instance;
	}

	@Override
	public void startUp() throws LWJGLException {
		Logger.info("Starting up Engine.");
		try {
			super.startUp();
			GLProgramManager.init();
			this.resized();
			this.setupWorld();
		} catch (Exception e) {
			Logger.error(e, "Faile to initialize the system.");
			super.shutDown();
		}
	}

	@Override
	public void shutDown() {
		Logger.info("Shutting down Engine.");
		super.shutDown();
	}

	@Override
	public void resized() {
		super.resized();
		GLProgramManager.resized(SysParam.SCREEN_WIDTH, SysParam.SCREEN_WIDTH);
	}

	@Override
	public void render() {
		super.render();
		this.updateFunction();
		M5CraftRenderer.render();
		
		this.exitOnGLError("loopCycle");
	}

	protected void update() {
		M5CraftUpdater.update();
	}

	protected void updateFunction() {
		while (Keyboard.next()) {
			if (!Keyboard.getEventKeyState()) {
				continue;
			}

			switch (Keyboard.getEventKey()) {
			case Keyboard.KEY_1:
				// textureSelector = 0;
				Logger.info("key 1");
				break;
			case Keyboard.KEY_2:
				// textureSelector = 1;
				Logger.info("key 2");
				break;
			}
		}
	}

	private void setupWorld() {
		WorldManager.loadWorld();
		this.exitOnGLError("setupWorld");
	}

	// ----------------------------------------------------------------private
	private static M5CraftEngine instance;
	private M5CraftEngine() {
	}
}
